<template>
  <div class="template-manager">
    <div class="template-actions">
      <el-button type="primary" size="small" @click="goToDesigner">
        <i class="el-icon-plus"></i>
        创建新模板
      </el-button>
      <el-button type="success" size="small" @click="refreshTemplates">
        <i class="el-icon-refresh"></i>
        刷新列表
      </el-button>
      <el-button type="warning" size="small" @click="clearAllTemplates">
        <i class="el-icon-delete"></i>
        清空所有模板
      </el-button>
    </div>

    <div class="template-content">
      <el-card v-if="templateList.length === 0" class="empty-state">
        <div class="empty-content">
          <i class="el-icon-document"></i>
          <h3>暂无模板</h3>
          <p>还没有保存任何表单模板</p>
          <!-- <el-button type="primary" @click="goToDesigner">
            <i class="el-icon-plus"></i>
            创建第一个模板
          </el-button> -->
        </div>
      </el-card>

      <el-card v-else>
        <div slot="header" class="table-header">
          <span>模板列表 ({{ templateList.length }} 个)</span>
          <div class="table-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索模板名称..."
              style="width: 200px; margin-right: 10px"
              clearable
              @input="handleSearch"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </div>
        </div>

        <el-table
          :data="filteredTemplateList"
          style="width: 100%"
          v-loading="loading"
          stripe
          border
        >
          <el-table-column prop="templateName" label="模板名称" min-width="200">
            <template slot-scope="scope">
              <div class="template-name">
                <i class="el-icon-document"></i>
                {{ scope.row.templateName }}
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" width="180">
            <template slot-scope="scope">
              <span>{{ formatDate(scope.row.createTime) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="creator" label="创建人" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.creator || "系统" }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="400" fixed="right">
            <template slot-scope="scope">
              <div class="table-actions">
                <el-button
                  size="mini"
                  type="text"
                  @click="useTemplate(scope.row)"
                  title="使用此模板"
                  class="action-btn use-btn"
                >
                  <i class="el-icon-edit"></i>
                  使用
                </el-button>

                <el-button
                  size="mini"
                  type="text"
                  @click="previewTemplate(scope.row)"
                  title="预览模板"
                  class="action-btn preview-btn"
                >
                  <i class="el-icon-view"></i>
                  预览
                </el-button>

                <el-button
                  size="mini"
                  type="text"
                  @click="editTemplate(scope.row)"
                  title="编辑模板内容"
                  class="action-btn edit-btn"
                >
                  <i class="el-icon-edit-outline"></i>
                  编辑
                </el-button>

                <el-button
                  size="mini"
                  type="text"
                  @click="deleteTemplate(scope.row)"
                  title="删除模板"
                  class="action-btn delete-btn"
                >
                  <i class="el-icon-delete"></i>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper" v-if="filteredTemplateList.length > 0">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredTemplateList.length"
          >
          </el-pagination>
        </div>
      </el-card>
    </div>

    <!-- 模板预览对话框 -->
    <el-dialog
      title="模板预览"
      :visible.sync="previewDialogVisible"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="preview-content">
        <div class="preview-info">
          <h3>{{ currentPreviewTemplate.templateName }}</h3>
          <p v-if="currentPreviewTemplate.description">
            {{ currentPreviewTemplate.description }}
          </p>
        </div>
        <div class="preview-form" v-if="currentPreviewTemplate.formJson">
          <v-form-render
            :form-json="currentPreviewTemplate.formJson"
            :form-data="previewFormData"
            :option-data="{}"
            ref="previewForm"
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="useTemplate(currentPreviewTemplate)">
          使用此模板
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "TemplateManager",
  data() {
    return {
      templateList: [],
      filteredTemplateList: [],
      searchKeyword: "",
      loading: false,
      currentPage: 1,
      pageSize: 10,
      previewDialogVisible: false,
      currentPreviewTemplate: {},
      previewFormData: {},
    };
  },
  async created() {
    await this.loadTemplates();
  },
  methods: {
    // 加载模板列表
    async loadTemplates() {
      this.loading = true;
      try {
        const { getTemplates } = await import("@/api");
        const templates = await getTemplates();

        this.templateList = templates.map((template) => ({
          ...template,
          creator: template.creator || "系统", // 如果没有创建人，默认为'系统'
        }));

        this.filteredTemplateList = [...this.templateList];
      } catch (error) {
        console.error("加载模板失败:", error);
        this.$message.error("加载模板失败: " + error.message);
        this.templateList = [];
        this.filteredTemplateList = [];
      } finally {
        this.loading = false;
      }
    },

    // 刷新模板列表
    refreshTemplates() {
      this.loadTemplates();
    },

    // 搜索模板
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        this.filteredTemplateList = [...this.templateList];
      } else {
        const keyword = this.searchKeyword.toLowerCase();
        this.filteredTemplateList = this.templateList.filter(
          (template) =>
            template.templateName.toLowerCase().includes(keyword) ||
            (template.creator &&
              template.creator.toLowerCase().includes(keyword))
        );
      }
      this.currentPage = 1; // 重置到第一页
    },

    // 使用模板
    useTemplate(template) {
      try {
        // 跳转到设计器页面，并传递模板ID
        this.$router.push(`/designer?templateId=${template.id}`);

        this.$message.success(`正在加载模板: ${template.templateName}`);
      } catch (error) {
        console.error("使用模板失败:", error);
        this.$message.error("使用模板失败: " + error.message);
      }
    },

    // 预览模板
    previewTemplate(template) {
      try {
        // 跳转到预览页面，并传递模板ID
        this.$router.push(`/preview?templateId=${template.id}`);
        this.$message.success(`正在预览模板: ${template.templateName}`);
      } catch (error) {
        console.error("预览模板失败:", error);
        this.$message.error("预览模板失败: " + error.message);
      }
    },

    // 复制模板JSON
    async copyTemplateJson(template) {
      try {
        const jsonString = JSON.stringify(template.formJson, null, 2);
        await navigator.clipboard.writeText(jsonString);
        this.$message.success("模板JSON已复制到剪贴板");
      } catch (error) {
        console.error("复制失败:", error);
        // 降级方案
        const textArea = document.createElement("textarea");
        textArea.value = JSON.stringify(template.formJson, null, 2);
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand("copy");
        document.body.removeChild(textArea);
        this.$message.success("模板JSON已复制到剪贴板");
      }
    },

    // 编辑模板
    editTemplate(template) {
      try {
        // 跳转到设计器页面，并传递模板ID进行编辑
        this.$router.push(`/designer?templateId=${template.id}`);
        this.$message.success(`正在编辑模板: ${template.templateName}`);
      } catch (error) {
        console.error("编辑模板失败:", error);
        this.$message.error("编辑模板失败: " + error.message);
      }
    },

    // 更新模板名称
    updateTemplateName(template, newName) {
      try {
        // 检查名称是否重复
        const existingTemplate = this.templateList.find(
          (t) => t.templateName === newName && t.id !== template.id
        );

        if (existingTemplate) {
          this.$message.error("模板名称已存在，请使用其他名称");
          return;
        }

        // 更新模板名称
        template.templateName = newName;
        template.updateTime = new Date().toISOString();

        // 保存到localStorage
        this.saveTemplatesToStorage();

        this.$message.success("模板名称更新成功");
        this.loadTemplates(); // 重新加载列表
      } catch (error) {
        console.error("更新模板名称失败:", error);
        this.$message.error("更新模板名称失败: " + error.message);
      }
    },

    // 删除模板
    deleteTemplate(template) {
      this.$confirm(
        `确定要删除模板 "${template.templateName}" 吗？此操作不可恢复。`,
        "删除确认",
        {
          confirmButtonText: "确定删除",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          try {
            // 从列表中移除模板
            const index = this.templateList.findIndex(
              (t) => t.id === template.id
            );
            if (index > -1) {
              this.templateList.splice(index, 1);
            }

            // 保存到localStorage
            this.saveTemplatesToStorage();

            // 更新过滤列表
            this.handleSearch();

            this.$message.success("模板删除成功");
          } catch (error) {
            console.error("删除模板失败:", error);
            this.$message.error("删除模板失败: " + error.message);
          }
        })
        .catch(() => {
          // 用户取消删除
        });
    },

    // 清空所有模板
    clearAllTemplates() {
      if (this.templateList.length === 0) {
        this.$message.info("没有模板需要清空");
        return;
      }

      this.$confirm(
        `确定要清空所有 ${this.templateList.length} 个模板吗？此操作不可恢复。`,
        "清空确认",
        {
          confirmButtonText: "确定清空",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          try {
            // 清空localStorage中的模板数据
            localStorage.removeItem("vform-templates");

            // 清空列表
            this.templateList = [];
            this.filteredTemplateList = [];

            this.$message.success("所有模板已清空");
          } catch (error) {
            console.error("清空模板失败:", error);
            this.$message.error("清空模板失败: " + error.message);
          }
        })
        .catch(() => {
          // 用户取消清空
        });
    },

    // 保存模板到localStorage
    saveTemplatesToStorage() {
      try {
        localStorage.setItem(
          "vform-templates",
          JSON.stringify(this.templateList)
        );
      } catch (error) {
        console.error("保存模板失败:", error);
        this.$message.error("保存模板失败: " + error.message);
      }
    },

    // 跳转到设计器
    goToDesigner() {
      this.$router.push("/designer");
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "-";
      try {
        const date = new Date(dateString);
        return date.toLocaleString("zh-CN", {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
        });
      } catch (error) {
        return dateString;
      }
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },

    handleCurrentChange(val) {
      this.currentPage = val;
    },
  },
};
</script>

<style scoped>
.template-manager {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-header h2 {
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-size: 28px;
}

.page-header p {
  color: #7f8c8d;
  margin: 0;
  font-size: 16px;
}

.template-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.template-content {
  margin-top: 20px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-content i {
  font-size: 64px;
  color: #ddd;
  margin-bottom: 20px;
}

.empty-content h3 {
  color: #909399;
  margin: 0 0 10px 0;
}

.empty-content p {
  color: #c0c4cc;
  margin: 0 0 20px 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

.table-actions {
  display: flex;
  align-items: center;
}

.template-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.template-name i {
  color: #409eff;
}

.no-description {
  color: #c0c4cc;
  font-style: italic;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.preview-content {
  max-height: 60vh;
  overflow-y: auto;
}

.preview-info {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.preview-info h3 {
  margin: 0 0 10px 0;
  color: #2c3e50;
}

.preview-info p {
  margin: 0;
  color: #606266;
}

.preview-form {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
}

/* 表格操作按钮样式 */
.table-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-btn {
  padding: 4px 8px !important;
  font-size: 12px !important;
  border-radius: 4px !important;
  transition: all 0.3s ease !important;
}

.action-btn:hover {
  background-color: rgba(64, 158, 255, 0.1) !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;
}

.use-btn:hover {
  color: #409eff !important;
  background-color: rgba(64, 158, 255, 0.1) !important;
}

.preview-btn:hover {
  color: #67c23a !important;
  background-color: rgba(103, 194, 58, 0.1) !important;
}

.edit-btn:hover {
  color: #e6a23c !important;
  background-color: rgba(230, 162, 60, 0.1) !important;
}

.delete-btn:hover {
  color: #f56c6c !important;
  background-color: rgba(245, 108, 108, 0.1) !important;
}

.action-btn i {
  margin-right: 4px;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .template-manager {
    padding: 15px;
  }

  .template-actions {
    flex-direction: column;
  }

  .template-actions .el-button {
    width: 100%;
  }

  .table-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .table-actions {
    justify-content: center;
  }

  .pagination-wrapper {
    text-align: center;
  }

  .table-actions {
    flex-wrap: wrap;
    gap: 4px;
  }

  .action-btn {
    font-size: 11px !important;
    padding: 3px 6px !important;
  }
}
</style>
